package com.kerwin.project.videolist.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kerwin.project.base.ProjectBaseDao;
import com.kerwin.project.videolist.entity.KVideo;
import com.kerwin.project.videolist.service.VideoService;

/**
 * 对Video相关操作的Service实现
 * @author KERWIN
 *
 */
@Service("videoService")
public class VideoServiceImpl implements VideoService {
	
	Logger logger = Logger.getLogger(getClass());

	@Resource(name = "projectBaseDao")
	private ProjectBaseDao<?> projectBaseDao;
	
	@Transactional
	public boolean addVideo(KVideo video) {
		boolean flag = true;
		if(null != video && StringUtils.isNotBlank(video.getVideoName())){
			try {
				video.setEnableFlag("1");			//可用
				video.setCreateDate(new Date());	//创建时间
				video.setDownloadNum(0L);			//默认下载次数为0
				logger.info("=======================保存Video方法开始执行:addVideo");
				Long id = (Long) this.projectBaseDao.save(video);
				if(null != id && id > 0){
					flag = true;
				}else{					
					flag = false;
				}
			} catch (Exception e) {
				logger.debug("保存Video方法执行失败:addVideo", e);
				flag = false;
			}
		}else {
			flag = false;			
		}
		return flag;
	}

	@SuppressWarnings("unchecked")
	public List<KVideo> findVideoList() {
		List<KVideo> videoList = new ArrayList<KVideo>();
		try {
			logger.info("=======================查询video方法开始执行:findVideoList");
			videoList = this.projectBaseDao.find(" FROM KVideo WHERE ENABLE_FLAG = 1 ORDER BY createDate DESC");
		} catch (Exception e) {
			logger.debug("查询video方法执行失败:findVideoList", e);
		}
		return videoList;
	}

	@SuppressWarnings("unchecked")
	public List<KVideo> findVideoDownloadList(int firstNum, int maxNum) {
		List<KVideo> videoList = new ArrayList<KVideo>();
		try {
			logger.info("=======================查询video方法开始执行:findVideoDownloadList");
			String hql = " FROM KVideo WHERE ENABLE_FLAG = 1 ORDER BY downloadNum ASC";
			videoList = this.projectBaseDao.findByLimit(hql, firstNum, maxNum, null);
		} catch (Exception e) {
			logger.debug("查询video方法执行失败:findVideoDownloadList", e);
		}
		return videoList;
	}

	@SuppressWarnings("unchecked")
	public KVideo findVideoById(Long id) {
		logger.info("=======================查询video方法开始执行:findVideoById");
		KVideo video = (KVideo) this.projectBaseDao.get(KVideo.class, id);
		return video;
	}

}
